package com.learn.algorithm_1_march;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Comparator;

/**
 * 另一种写法，更优雅
 */
public class LargestNumber2 {

    public static void main(String[] args) {
        int[] nums = {3,30,34,5,9};
        System.out.println("比较result：" + new LargestNumber2().useComparator(nums));
    }

    public String useComparator(int[] nums) {
        String[] arrs = new String[nums.length];
        for(int i = 0; i < nums.length; i++){
            arrs[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(arrs, new StringComparator());
        if (Integer.parseInt(arrs[0]) == 0){
            return "0";
        }
        else {
            StringBuilder builder = new StringBuilder();
            Arrays.asList(arrs).forEach(builder :: append);
            return builder.toString();
        }
    }

    /**
     * 使用比较器
     *      a > b时，a.compareTo(b) = 1；
     *      a = b时，a.compareTo(b) = 0；
     *      a < b时，a.compareTo(b) = -1；
     */
    private static class StringComparator implements Comparator<String>, Serializable{
        @Override
        public int compare(String var1, String var2) {
            //- 要取最大数，所以倒序
            return ((var2 + var1).compareTo(var1 + var2));
        }
    }

}
